package com.foss.push;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.foss.push.config.PushConstants;
import com.foss.push.socket.PushSetup;
import com.foss.push.socket.ServicePush;
import com.foss.push.socket.SocketConnect;

import android.content.Context;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.foss.push.zillasdk.Zilla;
import com.foss.push.zillasdk.ZillaDelegate;
import com.foss.push.config.Preferences;
import java.sql.SQLOutput;

/**
 * Created by zhouzhineng on 14-7-29.
 */
public class PushPlugin extends CordovaPlugin{

    public final static String TAG = "PushPlugin";

    public static final String REGISTER = "register";
    public static final String UNREGISTER = "unregister";
    public static final String EXIT = "exit";

    private static CordovaWebView gWebView;
    private static String gECB;
    private static String gSenderID;
    private static Bundle gCachedExtras = null;
    private static boolean gForeground = false;

    private Intent intent;

    private Context getApplicationContext() {
        return this.cordova.getActivity().getApplicationContext();
    }

    @Override
    public boolean execute(String action,String data, CallbackContext callbackContext) throws JSONException {
        System.out.println("push plugin");
        gWebView = this.webView;
        if(action.equals(REGISTER)) {
            register();
        } else if(action.equals(UNREGISTER)) {
            unregister();
        } else if(action.equals(EXIT)) {

        }
        return super.execute(action, data, callbackContext);
    }

    public void register() {
        IntentFilter filter = new IntentFilter(PushConstants.ACTION_REC_MESSAGE);
        getApplicationContext().registerReceiver(receiver, filter);
        if(intent == null) {
            intent = new Intent(getApplicationContext(), ServicePush.class);
        }
        Log.d(TAG,"PushPlugin---->register");
        authentication();

    }

    public void unregister() {
        try{
            getApplicationContext().unregisterReceiver(receiver);
        }catch (Exception e){
            e.printStackTrace();
        }

        if(intent != null) {
            getApplicationContext().stopService(intent);
        }

        Log.d(TAG,"PushPlugin---->unregister");
    }

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);
        gForeground = true;
    }

    @Override
    public void onPause(boolean multitasking) {
        super.onPause(multitasking);
        gForeground = false;
        final NotificationManager notificationManager = (NotificationManager) cordova.getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
    }

    @Override
    public void onResume(boolean multitasking) {
        super.onResume(multitasking);
        gForeground = true;
        IntentFilter filter = new IntentFilter(PushConstants.ACTION_REC_MESSAGE);
        getApplicationContext().registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        gForeground = false;
        gECB = null;
        gWebView = null;
        try{
            getApplicationContext().unregisterReceiver(receiver);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isInForeground()
    {
        return gForeground;
    }

    public static boolean isActive()
    {
        return gWebView != null;
    }

    private void authentication() {
        final Context context = getApplicationContext();
        ZillaDelegate delegate = new ZillaDelegate() {

            @Override
            public void requestSuccess(String json) {
                try {
                    if(json.equals("403")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage("应用验证失败");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        );
                        Dialog dialog = builder.create();
                        dialog.show();
                    } else if(json.equals("400")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(context);
                        builder.setTitle("提示");
                        builder.setMessage("应用已删除");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        );
                        Dialog dialog = builder.create();
                        dialog.show();
                    } else {
                        JSONObject jb = new JSONObject(json);
                        String token = jb.getString("token");
                        String expired = jb.getString("expired");
                        // 保存token和expired
                        Preferences.saveToken(token, expired);
                        Log.e("MainActivity","save token and expired");
                        // mPush.register();
                        getApplicationContext().startService(intent);
                    }

                } catch(JSONException e) {
                    e.printStackTrace();

                }

            }

            @Override
            public void requestStart() {
                // TODO Auto-generated method stub

            }

            @Override
            public void requestFailed(String errorMessage) {
                //Toast.makeText(MainActivity.this, "应用验证失败，请检查网络", Toast.LENGTH_SHORT).show();
                Log.e(TAG,"应用验证失败,请检查网络");

            }
        };
        Zilla.getZilla().appAuth(context, delegate);

    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(PushConstants.ACTION_REC_MESSAGE)) {
               String msg = intent.getStringExtra("msg");
                gWebView.sendJavascript("window.plugins.pushNotification.handlePushMsg(" + "\'"
                + msg + "\'" + ");");
                /*try{
                    JSONObject json = new JSONObject(msg);
                    if(json.has("id")) {
                        String msgId = json.getString("id");
                        Log.d(TAG,"the message Id == " + msgId);
                        receiptsMessage(getApplicationContext(),msgId);
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }*/

            }
        }
    };


}
